<?php

class LocationsController extends Controller
{

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/customer';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',

                'users' => array('@'),
            ),

            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Locations;
        $custno = Yii::app()->user->custno;
        $model->timezone = 'EST';
        $model->custno = $custno;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Locations'])) {

            $model->attributes = $_POST['Locations'];

            $model->taxcode = $model->state;
            $num = Yii::app()->db->createCommand('select max(cast(locno as unsigned)) from tbl_locations where custno=:custno')->queryScalar(array(
                'custno' => $model->custno,
            ));
            $model->locno = str_pad($num + 1, $model::LOCNO_LENGTH, '0', STR_PAD_LEFT);

            if ($model->save())
                $this->redirect(array('update', 'id' => $model->id));
        }
        $customer = Customers::model()->find('custno=:custno', array(
            'custno' => $model->custno,
        ));

        $this->render('create', array(
            'model' => $model,
            'customer' => $customer,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id);
        if ($model->custno != Yii::app()->user->custno) throw new CHttpException(404, 'The requested page does not exist.');
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Locations'])) {
            $model->attributes = $_POST['Locations'];
            $model->save();

        }
        $customer = Customers::model()->find('custno=:custno', array(
            'custno' => $model->custno,
        ));
        outputJsByList(Dispatchdetails::model()->getDepartmentList(), 'department');
        outputJsByList(Dispatchdetails::model()->getPriorityList(), 'priority');

        outputJsByList(JobsClass::getList(), 'job');
        Yii::app()->clientScript->registerScript('type', "var type='-1';", CClientScript::POS_HEAD);
        $caller = getUserRealname(Yii::app()->user->name);
        Yii::app()->clientScript->registerScript('caller', "var caller='$caller';", CClientScript::POS_HEAD);
        $this->render('update', array(
            'model' => $model,
            'customer' => $customer,

        ));
    }


    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $id = Yii::app()->user->custno;
        $customer = Customers::model()->find('custno=:custno', array('custno' => $id));
        $this->render('index', array(
            'customer' => $customer
        ));
    }


    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id)
    {
        $model = Locations::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'locations-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }


    public function actionGetLocationList($custno = NULL, $query = NULL, $page = 0, $sort = NULL, $dir = NULL,$status = NULL)
    {
        //we decrease $page by 1 because in Extjs first page is 1, but in our sql first page is 0;
        if ($page > 0) $page--;
        $order = CJSON::decode($sort);
        $criteria = new CDbCriteria();
        $criteria->compare('custno', $custno);
        if ($sort != NULL) {
            $criteria->order = $order[0]['property'] . ' ' . $order[0]['direction'];
        } else {
            $criteria->order = 'locno';
        }
if($query!=NULL){    
            $criteria->compare('locno',$query,true,'or');
            $criteria->compare('locname', $query, true, 'or');
            $criteria->compare('locnickname', $query, true, 'or');
            $criteria->compare('add1', $query, true, 'or');
            $criteria->compare('add2', $query, true, 'or');
            $criteria->compare('city', $query, true, 'or');
            $criteria->compare('state', $query, true, 'or');
            $criteria->compare('zip', $query, true, 'or');            
        }
if ($status != NULL || $status == 0)
		{
		    $criteria->compare('locationinactive', $status, false, 'and');   
		}
        $locations = new CActiveDataProvider('Locations', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 20,
                'currentPage' => $page,
            ),
        ));
        $rs = array();
        if (count($locations->getData()) > 0) {
            $rs['totalCount'] = $locations->getTotalItemCount();
            $rs['type'] = 'Locations';
            foreach ($locations->getData() as $item) {
                $rs['data'][] = $item->getAttributes();
            }
            echo json_encode($rs);

        }
        Yii::app()->end();
    }


}
